package com.eonmind.ai.mapper;

import com.eonmind.ai.dto.AiChatDto;
import com.eonmind.common.contract.data.base.BaseMongoMapper;
import com.eonmind.common.contract.enums.DelEnum;
import com.eonmind.common.provider.entity.ai.AiConversation;
import com.eonmind.user.contract.dto.UserInfoData;
import com.mongoplus.conditions.query.QueryWrapper;
import com.mongoplus.conditions.update.UpdateWrapper;
import com.mongoplus.model.PageResult;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class AiConversationMapper extends BaseMongoMapper<AiConversation> {


    public PageResult<AiConversation> page(UserInfoData userInfoData, AiChatDto.AiConversationPageRequest pageRequest) {
        if (ObjectUtils.isEmpty(pageRequest)) {
            return new PageResult<>();
        }
        QueryWrapper<AiConversation> mgoQuery = createMgoQuery()
                .eq(AiConversation::getUserId, userInfoData.getId())
                .likeLeft(StringUtils.isNotBlank(pageRequest.getKeyword()), AiConversation::getTitle, pageRequest.getKeyword())
                .eq(AiConversation::getDel, DelEnum.UN_DEL.getCode());
        return page(mgoQuery, pageRequest.getPage());
    }


    public AiConversation selectById(Long conversationId) {
        return one(createMgoQuery().eq(AiConversation::getId, conversationId)
                .eq(AiConversation::getDel, DelEnum.UN_DEL.getCode()));
    }

    public void incrementTotalToken(Long id, Integer totalTokens) {
        UpdateWrapper<AiConversation> inc =
                createMgoUpdate().inc(AiConversation::getTotalToken, totalTokens)
                        .eq(AiConversation::getId, id);
        update(inc);
    }
}
